using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCtrollor : MonoBehaviour
{
    public static class PlayerAttribute{
        public static float Health = 25;
        public static float MaxHealth = 50;
        public static int Defence = 0;
        public static bool OnGround;
    }
    public float Speed;
    public int JumpHeight;
    private float FallHeight;
    private new Rigidbody2D rigidbody;
    private BoxCollider2D Feet;
    public void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        Feet = GetComponent<BoxCollider2D>();
    }
    public void Update()
    {
        Run();
        CheckOnGround();
        if(Input.GetKeyDown(KeyCode.Space) && PlayerAttribute.OnGround){
            Jump();
        }
    }
    void Run(){
        float moveDir = Input.GetAxis("Horizontal");
        Vector2 playerVel = new(moveDir * Speed,rigidbody.velocity.y);
        rigidbody.velocity = playerVel;
    }
    void Jump(){
        Vector2 pVel = new(rigidbody.velocity.x,rigidbody.velocity.y + JumpHeight);
        rigidbody.velocity = pVel;
    }
    void CheckOnGround(){
        PlayerAttribute.OnGround = Feet.IsTouchingLayers(LayerMask.GetMask("Ground"));
        if(rigidbody.velocity.y <= -0.1f && !PlayerAttribute.OnGround){
            FallHeight = rigidbody.velocity.y;
        }
        if(PlayerAttribute.OnGround && FallHeight < -8.0f){
            PlayerAttribute.Health -= FallDamage();
            FallHeight = 0;
        }
    }
    float FallDamage(){
        float Damage = (float)(0 - ((FallHeight / 10.0f) - (PlayerAttribute.Defence * 0.2)));
        return Damage;
    }
}
